package com.xuqm.sdhbwfu.app.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.alertview.AlertView
import com.xuqm.base.App
import com.xuqm.base.adapter.CommonAdapter
import com.xuqm.base.adapter.ViewHolder
import com.xuqm.base.common.FileHelper
import com.xuqm.base.common.TimeHelper
import com.xuqm.base.common.ToolsHelper
import com.xuqm.base.dialog.loading.LoadingDialog
import com.xuqm.base.extensions.runWithPermission
import com.xuqm.base.extensions.showDialog
import com.xuqm.base.extensions.showMessage
import com.xuqm.base.ui.BaseActivity
import com.xuqm.sdhbwfu.app.MyApplication
import com.xuqm.sdhbwfu.app.R
import com.xuqm.sdhbwfu.app.common.PmTaskManage
import com.xuqm.sdhbwfu.app.data.SignData
import com.xuqm.sdhbwfu.app.data.SignMaterialData
import com.xuqm.sdhbwfu.app.data.SignSafetyData
import com.xuqm.sdhbwfu.app.data.SignToolData
import com.xuqm.sdhbwfu.app.databinding.ActivityMaintainBinding
import com.xuqm.sdhbwfu.app.model.PmTaskContent
import com.xuqm.sdhbwfu.app.model.PmTaskModel
import com.xuqm.sdhbwfu.app.ui.adapter.MaintainAdapter
import com.xuqm.sdhbwfu.app.ui.dialog.DialogPmSgin
import com.xuqm.sdhbwfu.app.ui.dialog.PopPmSginListener
import com.xuqm.sdhbwfu.app.viewmodel.MaintainViewModel
import com.xuqm.sdhbwfu.core.extensions.addItemDecorationForVertical
import com.xuqm.sdhbwfu.core.extensions.gone
import com.xuqm.sdhbwfu.core.extensions.invisible
import com.xuqm.sdhbwfu.core.extensions.visible
import java.io.File

/**
 * 实施主页
 */
class MaintainActivity : BaseActivity<ActivityMaintainBinding>(), View.OnClickListener {
    override fun getLayoutId(): Int = R.layout.activity_maintain
    override fun fullscreen(): Boolean = true

    private lateinit var currentItem: PmTaskContent
    private var cPosition: Int = 0
    private var cItem: Int = 0

    private val viewModel: MaintainViewModel by viewModels()

    private var current = 1
    private val adapter = MaintainAdapter()

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        binding.inspectionBackLyt.setOnClickListener {
            finish()
        }

        binding.tainListRv.layoutManager = LinearLayoutManager(mContext)
        binding.tainListRv.addItemDecorationForVertical(4)
        binding.tainListRv.adapter = adapter

        binding.popType5Rv.layoutManager = LinearLayoutManager(mContext)
        binding.popType5Rv.addItemDecorationForVertical(4)
        binding.popType5Rv.adapter = adapterChild

        binding.tainStepListRv.layoutManager = LinearLayoutManager(mContext)
        binding.tainStepListRv.addItemDecorationForVertical(4)
        binding.tainStepListRv.adapter = adapterStep


        binding.tainTitle.text = PmTaskManage.title

        adapter.setItemClickListener { _, item, position ->


            if ("MAINTAING" == item.taskStepExcuteStatus) onClickItem(item, position)

        }

        binding.tain1.setOnClickListener(this@MaintainActivity)
        binding.tain2.setOnClickListener(this@MaintainActivity)
        binding.tain3.setOnClickListener(this@MaintainActivity)
        binding.tain4.setOnClickListener(this@MaintainActivity)
        binding.tain5.setOnClickListener(this@MaintainActivity)
        binding.popBtn.setOnClickListener {

            if (binding.popType1.visibility == View.VISIBLE) {

                val str = binding.popType1Value.text
                if (!str.isNullOrEmpty()) {
                    currentItem.inputValueInfo = str.toString()
                    currentItem.taskStepExcuteStatus = "COMPLETE"
                    LoadingDialog.showDialog("")
                    viewModel.update(currentItem)
                }

            } else if (binding.popType9.visibility == View.VISIBLE) {

                val str = binding.type9Value.text
                if (!str.isNullOrEmpty()) {
                    currentItem.maintainSummary = str.toString()
                    currentItem.taskStepExcuteStatus = "COMPLETE"
                    LoadingDialog.showDialog("")
                    viewModel.submitExecutable(currentItem)
                }

            } else if (binding.popType5.visibility == View.VISIBLE) {
                currentItem.taskStepExcuteStatus = "COMPLETE"
                LoadingDialog.showDialog("")
                viewModel.submitExecutable(currentItem)
            } else if (binding.popType6.visibility == View.VISIBLE) {
                currentItem.taskStepExcuteStatus = "COMPLETE"
                LoadingDialog.showDialog("")
                viewModel.submitExecutable(currentItem)
            } else if (binding.popType7.visibility == View.VISIBLE) {
                currentItem.taskStepExcuteStatus = "COMPLETE"


                val taskStepExcuteDesc = binding.type7ItemErrMsg.text.toString()

                val referInfo1 = binding.type7Item1Value.text.toString()
                val referInfo2 = binding.type7Item2Value.text.toString()

                if (referInfo1.isEmpty() || referInfo2.isEmpty()) {
                    ToolsHelper.showMessage("请填写对应内容")
                    return@setOnClickListener
                }
                if (currentItem.taskStepExcutePhoto.isNullOrEmpty()) {
                    ToolsHelper.showMessage("请拍照上传")
                    return@setOnClickListener
                }

                if (taskStepExcuteDesc.isEmpty() && !currentItem.taskStepExcuteResultNormal!!) {
                    ToolsHelper.showMessage("请填写异常处理情况")
                    return@setOnClickListener
                }
                currentItem.configInfo?.item?.get(0)?.referInfo = referInfo1
                currentItem.configInfo?.item?.get(1)?.referInfo = referInfo2
                currentItem.taskStepExcuteDesc = taskStepExcuteDesc
                currentItem.taskStepExcuteStatus = "COMPLETE"
                LoadingDialog.showDialog("")
                viewModel.submitExecutable(currentItem)
            } else if (binding.tainStepListRv.visibility == View.VISIBLE) {

                showDialog("提示", "确认完成维护任务吗吗？", {
                    viewModel.finish(PmTaskManage.stepMain.id)
                }, {})
            }

            initUiChild()

            refreshStatus()
        }
        binding.popBtnType5.setOnClickListener {
            startActivityForResult(
                Intent(
                    mContext,
                    PmMaterialActivity::class.java
                ).apply { putExtra("position", -1) }, 10086
            )
        }
        binding.popBtnStep.setOnClickListener {
            startActivityForResult(
                Intent(
                    mContext,
                    PmAddObjActivity::class.java
                ).apply { putExtra("position", -1) }, 10010
            )
        }

        //异常拍照
        binding.type7ItemCamera.setOnClickListener {
            runWithPermission(
                Manifest.permission.CAMERA,
                rationaleMethod = {
                    AlertView(
                        "无法获取摄像头使用权限", "上传附件需要开启相机权限才能使用。",
                        null, arrayOf("确定"), null, mContext,
                        AlertView.Style.Alert
                    ) { _, _ ->
                    }.show()
                },
                permanentDeniedMethod = {
                    "请在设置界面打开摄像头权限".showMessage()
                    AlertView(
                        "无法获取摄像头使用权限", "上传附件需要开启相机权限才能使用，请在应用权限管理页面打开相关权限。",
                        null, arrayOf("确定"), null, mContext,
                        AlertView.Style.Alert
                    ) { _, _ ->
                    }.show()
                },
                callback = {
                    dispatchTakePictureIntent()
                })
        }
        //type7状态选择
        binding.type7ItemNormal.setOnClickListener {
            currentItem.taskStepExcuteResultNormal = true
            binding.type7ItemNormal.setBackgroundResource(R.drawable.bg_btn_blue_line)
            binding.type7ItemErr.setBackgroundResource(R.drawable.bg_btn_white_line)
        }
        //type7状态选择
        binding.type7ItemErr.setOnClickListener {
            currentItem.taskStepExcuteResultNormal = false
            binding.type7ItemErr.setBackgroundResource(R.drawable.bg_btn_red_line)
            binding.type7ItemNormal.setBackgroundResource(R.drawable.bg_btn_white_line)
        }
    }

    private fun initUiChild() {
        binding.popBtn.visibility = View.INVISIBLE
        binding.popBtnType5.visibility = View.GONE
        binding.popBtnStep.visibility = View.GONE
        binding.tainListRv.visibility = View.GONE
        binding.tainStepListRv.visibility = View.GONE
        binding.popType1.visibility = View.GONE
        binding.popType3.visibility = View.GONE
        binding.popType4.visibility = View.GONE
        binding.popType5.visibility = View.GONE
        binding.popType9.visibility = View.GONE
        binding.popType6.visibility = View.GONE
        binding.popType7.visibility = View.GONE
        binding.popType8.visibility = View.GONE
        if (current == 5)
            binding.tainStepListRv.visibility = View.VISIBLE
        else
            binding.tainListRv.visibility = View.VISIBLE
    }

    private fun onClickItem(item: PmTaskContent, position: Int) {

        currentItem = item
        cPosition = position

        when (item.type) {
            "input" -> {//输入框
                binding.popBtn.visibility = View.VISIBLE
                binding.popType1.visibility = View.VISIBLE
                binding.tainListRv.visibility = View.GONE

                binding.popType1Index.text = "${position + 1}"
                binding.popType1Title.text = item.title
                binding.popType1Value.setText("")
                binding.popType1Name.text = item.label
            }
            "签字确认" -> {//签名

                DialogPmSgin.showDialog(mContext, object : PopPmSginListener {
                    override fun confirm(img: Bitmap) {
                        LoadingDialog.dismissDialog()
                        viewModel.signUpload(img)
                    }
                })
            }
            "维护总结" -> {//签名
                binding.popBtn.visibility = View.VISIBLE
                binding.popType9.visibility = View.VISIBLE
                binding.tainListRv.visibility = View.GONE

                binding.type9Value.setText("")
            }
            "preparation" -> {//备料
                binding.popBtn.visibility = View.VISIBLE
                binding.popType5.visibility = View.VISIBLE
                binding.popBtnType5.visibility = View.VISIBLE
                binding.tainListRv.visibility = View.GONE

                adapterChild.setmDatas(item.configInfo?.dataList)

            }
            "noOperation" -> {//不需要操作
                binding.popBtn.visibility = View.VISIBLE
                binding.popType6.visibility = View.VISIBLE
                binding.tainListRv.visibility = View.GONE

                binding.popType6Index.text = "${position + 1}"
                binding.popType6Title.text = item.title

            }
            "measured" -> {//不需要操作
                binding.popBtn.visibility = View.VISIBLE
                binding.popType7.visibility = View.VISIBLE
                binding.tainListRv.visibility = View.GONE

                binding.popType7Index.text = "${position + 1}"
                binding.popType7Title.text = item.title

                currentItem.taskStepExcuteResultNormal = true
                binding.type7Item1.text =
                    "${item.configInfo?.item?.get(0)?.colName}(${item.configInfo?.item?.get(0)?.unit})"
                binding.type7Item2.text =
                    "${item.configInfo?.item?.get(1)?.colName}(${item.configInfo?.item?.get(1)?.unit})"

            }
//            2 -> {//签名
//                binding.popBtn.visibility = View.VISIBLE
//                binding.popType2.visibility = View.VISIBLE
//                binding.tainListRv.visibility = View.GONE
//
//
//            }
//            3 -> {//表格过流保护
//                binding.popBtn.visibility = View.VISIBLE
//                binding.popType3.visibility = View.VISIBLE
//                binding.tainListRv.visibility = View.GONE
//            }
//            4 -> {//表格-电压
//                binding.popBtn.visibility = View.VISIBLE
//                binding.popType4.visibility = View.VISIBLE
//                binding.tainListRv.visibility = View.GONE
//            }
        }


    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {
        super.initData()

        viewModel.status_err.observe(this) {
            LoadingDialog.dismissDialog()
            currentItem.taskStepExcutePhoto = it.fsId
        }
        viewModel.status_sgin.observe(this) {
            LoadingDialog.dismissDialog()
            when (current) {
                1 -> {
                    PmTaskManage.firstCondition.contents[cPosition].label = it.fsId
                    viewModel.submitFirst(
                        SignData(
                            it.fsId,
                            PmTaskManage.firstId
                        )
                    )
                }

                2 -> {
                    PmTaskManage.safetyGuarantee.contents[cPosition].label = it.fsId
                    viewModel.submitSafety(
                        SignSafetyData(
                            it.fsId,
                            PmTaskManage.firstId
                        )
                    )
                }

                3 -> {
                    PmTaskManage.toolPreparation.contents[cPosition].label = it.fsId
                    viewModel.submitTool(
                        SignToolData(
                            it.fsId,
                            PmTaskManage.firstId
                        )
                    )
                }

                4 -> {
                    PmTaskManage.materialPreparation.contents[cPosition].label = it.fsId
                    viewModel.submitMaterial(
                        SignMaterialData(
                            it.fsId,
                            PmTaskManage.firstId
                        )
                    )
                }

            }
            initUiChild()
            refreshStatus()
        }
        viewModel.status.observe(this) {
            LoadingDialog.dismissDialog()

            refreshItem(it)

            refreshStatus()
            adapter.notifyDataSetChanged()
        }

        viewModel.statusFinish.observe(this) {
            LoadingDialog.dismissDialog()
            finish()
        }
        viewModel.statusCreate.observe(this) {
            LoadingDialog.dismissDialog()
        }
        viewModel.statusSign.observe(this) {
            LoadingDialog.dismissDialog()

            if (!it.isNullOrEmpty()) when (current) {
                1 -> {
                    PmTaskManage.firstCondition.contents[cPosition].updateTime = it
                    PmTaskManage.firstCondition.firstConditionStatus = "COMPLETE"
                }
                2 -> {
                    PmTaskManage.safetyGuarantee.contents[cPosition].updateTime = it
                    PmTaskManage.safetyGuarantee.safetyGuaranteeStatus = "COMPLETE"
                }
                3 -> {
                    PmTaskManage.toolPreparation.contents[cPosition].updateTime = it
                    PmTaskManage.toolPreparation.toolPreparationStatus = "COMPLETE"
                }
                4 -> {
                    PmTaskManage.materialPreparation.contents[cPosition].updateTime = it
                    PmTaskManage.materialPreparation.materialPreparationStatus = "COMPLETE"
                }
                5 -> {
                    PmTaskManage.stepMain.items[cItem].contents[cPosition].updateTime = it
                    PmTaskManage.stepMain.items[cItem].stepMainStatus = "COMPLETE"
                }
            }

            refreshItem(!it.isNullOrEmpty())

            refreshStatus()
            adapter.notifyDataSetChanged()
        }


        if (PmTaskManage.firstCondition.contents[PmTaskManage.firstCondition.contents.size - 1].type != "签字确认") {
            val item = PmTaskManage.firstCondition.contents[0].copy()

            if (PmTaskManage.firstCondition.firstConditionSign.isNullOrEmpty()) {
                item.taskStepExcuteStatus = "NOTSTART"
                item.title = "签字确认"
                item.type = "签字确认"
            } else {
                item.taskStepExcuteStatus = "COMPLETE"
                item.title = "签字确认"
                item.type = "签字确认"
                item.updateTime = PmTaskManage.firstCondition.endTime
                item.label = PmTaskManage.firstCondition.firstConditionSign
            }

            PmTaskManage.firstCondition.contents.add(item)
        }
        if (PmTaskManage.safetyGuarantee.contents[PmTaskManage.safetyGuarantee.contents.size - 1].type != "签字确认") {
            val item = PmTaskManage.safetyGuarantee.contents[0].copy()

            if (PmTaskManage.safetyGuarantee.safetyGuaranteeSign.isNullOrEmpty()) {
                item.taskStepExcuteStatus = "NOTSTART"
                item.title = "签字确认"
                item.type = "签字确认"
            } else {
                item.taskStepExcuteStatus = "COMPLETE"
                item.title = "签字确认"
                item.type = "签字确认"
                item.updateTime = PmTaskManage.safetyGuarantee.endTime
                item.label = PmTaskManage.safetyGuarantee.safetyGuaranteeSign
            }

            PmTaskManage.safetyGuarantee.contents.add(item)
        }
        if (PmTaskManage.toolPreparation.contents[PmTaskManage.toolPreparation.contents.size - 1].type != "签字确认") {
            val item = PmTaskManage.toolPreparation.contents[0].copy()

            if (PmTaskManage.toolPreparation.toolPreparationSign.isNullOrEmpty()) {
                item.taskStepExcuteStatus = "NOTSTART"
                item.title = "签字确认"
                item.type = "签字确认"
            } else {
                item.taskStepExcuteStatus = "COMPLETE"
                item.title = "签字确认"
                item.type = "签字确认"
                item.updateTime = PmTaskManage.toolPreparation.endTime
                item.label = PmTaskManage.toolPreparation.toolPreparationSign
            }

            PmTaskManage.toolPreparation.contents.add(item)
        }
        if (PmTaskManage.materialPreparation.contents[PmTaskManage.materialPreparation.contents.size - 1].type != "签字确认") {
            val item = PmTaskManage.materialPreparation.contents[0].copy()

            if (PmTaskManage.materialPreparation.materialPreparationSign.isNullOrEmpty()) {
                item.taskStepExcuteStatus = "NOTSTART"
                item.title = "签字确认"
                item.type = "签字确认"
            } else {
                item.taskStepExcuteStatus = "COMPLETE"
                item.title = "签字确认"
                item.type = "签字确认"
                item.updateTime = PmTaskManage.materialPreparation.endTime
                item.label = PmTaskManage.materialPreparation.materialPreparationSign
            }

            PmTaskManage.materialPreparation.contents.add(item)
        }

        adapter.setmDatas(PmTaskManage.firstCondition.contents)
        refreshStatus()

    }

    private fun refreshItem(it: Boolean) {

        if (!it) {
            when (current) {
                1 -> PmTaskManage.firstCondition.contents[cPosition].taskStepExcuteStatus =
                    "MAINTAING"
                2 -> PmTaskManage.safetyGuarantee.contents[cPosition].taskStepExcuteStatus =
                    "MAINTAING"
                3 -> PmTaskManage.toolPreparation.contents[cPosition].taskStepExcuteStatus =
                    "MAINTAING"
                4 -> PmTaskManage.materialPreparation.contents[cPosition].taskStepExcuteStatus =
                    "MAINTAING"
                5 -> PmTaskManage.stepMain.items[cItem].contents[cPosition].taskStepExcuteStatus =
                    "MAINTAING"
            }
        } else
            when (current) {
                1 -> {
                    PmTaskManage.firstCondition.contents[cPosition].taskStepExcuteStatus =
                        "COMPLETE"
                    if (PmTaskManage.firstCondition.contents.size > cPosition + 1) {
                        PmTaskManage.firstCondition.firstConditionStatus = "EXCUTE"
                    }
                }
                2 -> {
                    PmTaskManage.safetyGuarantee.contents[cPosition].taskStepExcuteStatus =
                        "COMPLETE"
                    if (PmTaskManage.safetyGuarantee.contents.size > cPosition + 1) {
                        PmTaskManage.safetyGuarantee.safetyGuaranteeStatus = "EXCUTE"
                    }
                }
                3 -> {
                    PmTaskManage.toolPreparation.contents[cPosition].taskStepExcuteStatus =
                        "COMPLETE"
                    if (PmTaskManage.toolPreparation.contents.size > cPosition + 1) {
                        PmTaskManage.toolPreparation.toolPreparationStatus = "EXCUTE"
                    }
                }
                4 -> {
                    PmTaskManage.materialPreparation.contents[cPosition].taskStepExcuteStatus =
                        "COMPLETE"
                    if (PmTaskManage.materialPreparation.contents.size > cPosition + 1) {
                        PmTaskManage.materialPreparation.materialPreparationStatus = "EXCUTE"
                    }
                }
                5 -> {
                    PmTaskManage.stepMain.items[cItem].contents[cPosition].taskStepExcuteStatus =
                        "COMPLETE"
                    if (PmTaskManage.stepMain.items[cItem].contents.size > cPosition + 1) {
                        PmTaskManage.stepMain.items[cItem].stepMainStatus = "EXCUTE"
                    }
                }
            }
    }

    private fun refreshStatus() {

        if ("UNSTART" == PmTaskManage.firstCondition.firstConditionStatus) {
            PmTaskManage.firstCondition.contents[0].taskStepExcuteStatus = "MAINTAING"
        } else if ("COMPLETE" == PmTaskManage.firstCondition.firstConditionStatus) {
            if ("UNSTART" == PmTaskManage.safetyGuarantee.safetyGuaranteeStatus) {
                PmTaskManage.safetyGuarantee.contents[0].taskStepExcuteStatus = "MAINTAING"
            } else if ("COMPLETE" == PmTaskManage.safetyGuarantee.safetyGuaranteeStatus) {
                if ("UNSTART" == PmTaskManage.toolPreparation.toolPreparationStatus) {
                    PmTaskManage.toolPreparation.contents[0].taskStepExcuteStatus = "MAINTAING"
                } else if ("COMPLETE" == PmTaskManage.toolPreparation.toolPreparationStatus) {
                    if ("UNSTART" == PmTaskManage.materialPreparation.materialPreparationStatus) {
                        PmTaskManage.materialPreparation.contents[0].taskStepExcuteStatus =
                            "MAINTAING"
                    } else if ("COMPLETE" == PmTaskManage.materialPreparation.materialPreparationStatus) {
                    } else {
                        for (content in PmTaskManage.materialPreparation.contents) {
                            if (content.taskStepExcuteStatus == "MAINTAING") {
                                break
                            } else if (content.taskStepExcuteStatus == "NOTSTART") {
                                content.taskStepExcuteStatus = "MAINTAING"
                                break
                            }
                        }
                    }
                } else {
                    for (content in PmTaskManage.toolPreparation.contents) {
                        if (content.taskStepExcuteStatus == "MAINTAING") {
                            break
                        } else if (content.taskStepExcuteStatus == "NOTSTART") {
                            content.taskStepExcuteStatus = "MAINTAING"
                            break
                        }
                    }
                }
            } else {
                for (content in PmTaskManage.safetyGuarantee.contents) {
                    if (content.taskStepExcuteStatus == "MAINTAING") {
                        break
                    } else if (content.taskStepExcuteStatus == "NOTSTART") {
                        content.taskStepExcuteStatus = "MAINTAING"
                        break
                    }
                }
            }
        } else {
            for (content in PmTaskManage.firstCondition.contents) {
                if (content.taskStepExcuteStatus == "MAINTAING") {
                    break
                } else if (content.taskStepExcuteStatus == "NOTSTART") {
                    content.taskStepExcuteStatus = "MAINTAING"
                    break
                }
            }
        }
        adapter.notifyDataSetChanged()
    }

    private fun notifyDataSetChanged() {

        when (current) {
            1 -> {
                adapter.setmDatas(PmTaskManage.firstCondition.contents)
                binding.tainListRv.visible()
                binding.tainStepListRv.gone()
            }
            2 -> {
                adapter.setmDatas(PmTaskManage.safetyGuarantee.contents)
                binding.tainListRv.visible()
                binding.tainStepListRv.gone()
            }
            3 -> {
                adapter.setmDatas(PmTaskManage.toolPreparation.contents)
                binding.tainListRv.visible()
                binding.tainStepListRv.gone()
            }
            4 -> {
                adapter.setmDatas(PmTaskManage.materialPreparation.contents)
                binding.tainListRv.visible()
                binding.tainStepListRv.gone()
            }
            5 -> {
                adapterStep.setmDatas(PmTaskManage.stepMain.items)
                binding.tainStepListRv.visible()
                binding.tainListRv.gone()
                binding.popBtnStep.visible()
                binding.popBtn.visible()
            }
        }


    }

    override fun onClick(v: View) {
        binding.tain1Tv.setTextColor(Color.parseColor("#555354"))
        binding.tain2Tv.setTextColor(Color.parseColor("#555354"))
        binding.tain3Tv.setTextColor(Color.parseColor("#555354"))
        binding.tain4Tv.setTextColor(Color.parseColor("#555354"))
        binding.tain5Tv.setTextColor(Color.parseColor("#555354"))

        binding.tain1Line.setBackgroundColor(Color.parseColor("#d8d8d8"))
        binding.tain2Line.setBackgroundColor(Color.parseColor("#d8d8d8"))
        binding.tain3Line.setBackgroundColor(Color.parseColor("#d8d8d8"))
        binding.tain4Line.setBackgroundColor(Color.parseColor("#d8d8d8"))
        binding.tain5Line.setBackgroundColor(Color.parseColor("#d8d8d8"))

        when (v.id) {
            R.id.tain_1 -> {
                current = 1
                binding.tain1Tv.setTextColor(Color.parseColor("#2194D3"))
                binding.tain1Line.setBackgroundColor(Color.parseColor("#2194D3"))
            }
            R.id.tain_2 -> {
                current = 2
                binding.tain2Tv.setTextColor(Color.parseColor("#2194D3"))
                binding.tain2Line.setBackgroundColor(Color.parseColor("#2194D3"))
            }
            R.id.tain_3 -> {
                current = 3
                binding.tain3Tv.setTextColor(Color.parseColor("#2194D3"))
                binding.tain3Line.setBackgroundColor(Color.parseColor("#2194D3"))
            }
            R.id.tain_4 -> {
                current = 4
                binding.tain4Tv.setTextColor(Color.parseColor("#2194D3"))
                binding.tain4Line.setBackgroundColor(Color.parseColor("#2194D3"))
            }
            R.id.tain_5 -> {
                current = 5
                binding.tain5Tv.setTextColor(Color.parseColor("#2194D3"))
                binding.tain5Line.setBackgroundColor(Color.parseColor("#2194D3"))
            }
        }
        initUiChild()
        notifyDataSetChanged()

    }

    private val adapterChild =
        object : CommonAdapter<PmTaskContent.ConfigInfo.Data>(R.layout.item_pm_material) {
            override fun convert(
                holder: ViewHolder,
                item: PmTaskContent.ConfigInfo.Data,
                position: Int
            ) {
                holder.setBackgroundColor(R.id.item_app, Color.parseColor("#DBE3E6"))
                holder.setText(R.id.item_job_no, "${position + 1}")
                holder.setText(R.id.item_job_name, item.specification)
                holder.setText(R.id.item_job_obj, item.name)
                holder.setText(R.id.item_job_type, "${item.quantity}")

                holder.setClickListener(R.id.item_pm_del) {
                    removeItem(item)
                }
                holder.setClickListener(R.id.item_pm_edit) {
                    startActivityForResult(
                        Intent(
                            mContext,
                            PmMaterialActivity::class.java
                        ).apply {
                            putExtra("position", position)
                            putExtra("name", item.name)
                            putExtra("specification", item.specification)
                            putExtra("quantity", item.quantity)
                        }, 10086
                    )
                }
            }

        }
    private val adapterStep =
        object : CommonAdapter<PmTaskModel.StepMain.Item>(R.layout.item_maintain_step) {
            override fun convert(
                holder: ViewHolder,
                item: PmTaskModel.StepMain.Item,
                position: Int
            ) {
                holder.setText(R.id.name, item.assetName)
                holder.setText(R.id.createTime, item.createTime)
                holder.setText(R.id.endTime, item.endTime)

                if ("COMPLETE" == item.stepMainStatus) {
                    holder.setText(R.id.item_maintain_1_status, "完成")
                    holder.setBackgroundResource(
                        R.id.item_maintain_1_status,
                        R.drawable.maintain_status_normal
                    )
                } else {
                    holder.setText(R.id.item_maintain_1_status, "维护中")
                    holder.setBackgroundResource(
                        R.id.item_maintain_1_status,
                        R.drawable.maintain_status_ing
                    )
                    holder.setClickListener(R.id.item_maintain_1_status) {

                        if ("UNSTART" == item.stepMainStatus) {
                            item.contents[0].taskStepExcuteStatus =
                                "MAINTAING"
                        } else if ("EXCUTE" == item.stepMainStatus) {
                            for (content in item.contents) {
                                if (content.taskStepExcuteStatus == "MAINTAING") {
                                    break
                                } else if (content.taskStepExcuteStatus == "NOTSTART") {
                                    content.taskStepExcuteStatus = "MAINTAING"
                                    break
                                }
                            }
                        }


                        if (item.contents[item.contents.size - 2].type != "维护总结") {
                            val ite = item.contents[0].copy()

                            if (item.maintainSummary.isNullOrEmpty()) {
                                ite.taskStepExcuteStatus = "NOTSTART"
                                ite.title = "维护总结"
                                ite.type = "维护总结"
                            } else {
                                ite.taskStepExcuteStatus = "COMPLETE"
                                ite.title = "维护总结"
                                ite.type = "维护总结"
                                ite.label = item.maintainSummary
                            }

                            item.contents.add(ite)
                        }
                        if (item.contents[item.contents.size - 1].type != "签字确认") {
                            val ite = item.contents[0].copy()

                            if (item.bankMangerSign.isNullOrEmpty()) {
                                ite.taskStepExcuteStatus = "NOTSTART"
                                ite.title = "签字确认"
                                ite.type = "签字确认"
                            } else {
                                ite.taskStepExcuteStatus = "COMPLETE"
                                ite.title = "签字确认"
                                ite.type = "签字确认"
                                ite.updateTime = item.endTime
                                ite.implementerSign = item.implementerSign
                                ite.followConstructerSign = item.followConstructerSign
                                ite.bankMangerSign = item.bankMangerSign
                            }

                            item.contents.add(ite)
                        }




                        adapter.setmDatas(item.contents)
                        binding.popBtnStep.gone()
                        binding.popBtn.invisible()
                        binding.tainListRv.visible()
                        binding.tainStepListRv.gone()
                    }
                }
            }

        }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == 10086) {
            val p = data?.getIntExtra("position", -1)
            if (-1 == p) {
                currentItem.configInfo?.dataList?.add(
                    PmTaskContent.ConfigInfo.Data(
                        data.getStringExtra("name")!!,
                        data.getIntExtra("quantity", 0),
                        data.getStringExtra("specification")!!,
                    )
                )
            } else {
                currentItem.configInfo?.dataList?.get(p!!)?.also {
                    it.name = data.getStringExtra("name")!!
                    it.quantity = data.getIntExtra("quantity", 0)
                    it.specification = data.getStringExtra("specification")!!
                }
            }
            adapterChild.setmDatas(currentItem.configInfo?.dataList)

        } else if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if (resultCode == RESULT_OK) {
                viewModel.errUpload(photoPath)
            }

        } else if (resultCode == RESULT_OK && requestCode == 10010) {

            data?.also {
                App.getInstance().runOnUiThread { LoadingDialog.showDialog("") }
                viewModel.createItem(
                    PmTaskManage.stepMain.id,
                    data.getStringExtra("code")!!,
                    data.getStringExtra("name")!!
                )
            }

        }
    }

    lateinit var photoPath: String
    val REQUEST_IMAGE_CAPTURE = 10013

    private fun dispatchTakePictureIntent() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            val c: ComponentName? = takePictureIntent.resolveActivity(packageManager)
            if (null == c) {
                "启动相机失败".showMessage()
            } else {
                val photoURI = FileHelper.getFileUri(
                    File.createTempFile(
                        TimeHelper.getTimeMillis().toString(),
                        ".jpg",
                        File(FileHelper.getImagePath())
                    ).also { photoPath = it.absolutePath }
                )

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            }
        }
    }
}